<template>
  <div class="container_warp">
    <div id="containerChart"></div>
    <RightDrawer class="right_drawer" :drawerType="type" :selectCell="selectCell" :graph="graph" :grid="grid"
      @deleteNode="deleteNode"></RightDrawer>
    <div class="operating">
      <div class="btn-group">
        <div class="btn" title="圆形节点" @mousedown="startDrag('Circle', $event)">
          <i class="iconfont icon-circle"></i>
        </div>
        <div class="btn" title="正方形节点" @mousedown="startDrag('Rect', $event)">
          <i class="iconfont icon-square"></i>
        </div>
        <div class="btn" title="条件节点">
          <i class="iconfont icon-square rotate-square" @mousedown="startDrag('polygon', $event)"></i>
        </div>
        <div class="btn-group_tips" v-if="showTips">
          拖拽生成</br>资产拓扑图形
        </div>
      </div>
      <div class="btn-group">
        <el-tooltip content="直线箭头" placement="bottom">
          <div :class="['btn', currentArrow === 1 ? 'currentArrow' : '']" @click="changeEdgeType('normal')">
            <i class="iconfont icon-ai28"></i>
          </div>
        </el-tooltip>
        <el-tooltip content="曲线箭头" placement="bottom">
          <div :class="['btn', currentArrow === 2 ? 'currentArrow' : '']" @click="changeEdgeType('smooth')">
            <i class="iconfont icon-Down-Right"></i>
          </div>
        </el-tooltip>
        <el-tooltip content="直角箭头" placement="bottom">
          <div :class="['btn', currentArrow === 3 ? 'currentArrow' : '']" @click="changeEdgeType()">
            <i class="iconfont icon-jiantou"></i>
          </div>
        </el-tooltip>
        <el-tooltip content="上一步" placement="bottom">
          <div class="btn" @click="beforeStep()">
            <i class="el-icon-caret-left"></i>
          </div>
        </el-tooltip>
        <el-tooltip content="下一步" placement="bottom">
          <div class="btn" @click="nextStep()">
            <i class="el-icon-caret-right"></i>
          </div>
        </el-tooltip>
      </div>
      <!-- <div class="btn-group">
          <div class="btn" @click="changeMode('edit')" title="选择模式">
            <i class="iconfont icon-mousepointershubiao"></i>
          </div>
          <div class="btn" @click="changeMode('drag')" title="拖拽模式">
            <i class="iconfont icon-tuozhuai"></i>
          </div>
        </div> -->
      <div class="btn-group">
        <el-tooltip content="删除" placement="bottom">
          <div class="btn" @click="deleteNode()" style="margin-top: 5px;">
            <i class="iconfont icon-shanchu"></i>
          </div>
        </el-tooltip>
        <el-tooltip content="保存PNG" placement="bottom">
          <div class="btn" @click="saveToPNG()" title="保存">
            <i class="el-icon-picture"></i>
          </div>
        </el-tooltip>
        <el-tooltip content="保存数据" placement="bottom">
          <div class="btn" @click="saveData()" title="保存">
            <i class="iconfont icon-baocun"></i>
          </div>
        </el-tooltip>
      </div>
    </div>
  </div>

</template>
<script>
import '@antv/x6-vue-shape'
import { Graph, Shape, Addon, FunctionExt, DataUri } from '@antv/x6';
import RightDrawer from '../components/RightDrawer';
import insertCss from 'insert-css';
import { startDragToGraph } from '../Graph/methods.js'
const data = {};
export default {
  data() {
    return {
      graph: '',
      value1: true,
      type: 'grid',
      selectCell: '',
      connectEdgeType: {  //连线方式
        connector: 'normal',
        router: {
          name: ''
        }
      },
      showTips: false,
      currentArrow: 1,
      grid: { // 网格设置
        size: 20,      // 网格大小 10px
        visible: true, // 渲染网格背景
        type: 'mesh',
        args: {
          color: '#D0D0D0',
          thickness: 1,     // 网格线宽度/网格点大小
          factor: 10,
        },
      },
      // 当前选中或者默认的节点数据
      currentNode: {},
    }
  },
  components: {
    RightDrawer
  },
  methods: {
    initX6() {
      var _that = this
      this.graph = new Graph({
        history: true, // 开启历史记录功能
        // 页面缩放
        mousewheel: {
          enabled: true,
          modifiers: ['ctrl', 'meta'],
        },
        container: document.getElementById('containerChart'),
        width: 1200,
        height: '100%',
        grid: _that.grid,
        resizing: { //调整节点宽高
          enabled: true,
          orthogonal: false,
        },
        selecting: true, //可选
        snapline: true,
        interacting: {
          edgeLabelMovable: true
        },
        connecting: { // 节点连接
          anchor: 'center',
          connectionPoint: 'anchor',
          allowBlank: false,
          snap: true,
          createEdge() {
            return new Shape.Edge({
              attrs: {
                line: {
                  stroke: '#1890ff',
                  strokeWidth: 1,

                  targetMarker: {
                    name: 'classic',
                    size: 8
                  },
                  strokeDasharray: 0, //虚线
                  style: {
                    animation: 'ant-line 30s infinite linear',
                  },
                },
              },
              labels: [
                {
                  attrs: { label: { text: '', id: '' } },
                },
              ],
              connector: _that.connectEdgeType.connector,
              router: {
                name: _that.connectEdgeType.router.name || ''
              },
              zIndex: 0
            })
          },
        },
        highlighting: {
          magnetAvailable: {
            name: 'stroke',
            args: {
              padding: 4,
              attrs: {
                strokeWidth: 4,
                stroke: '#6a6c8a'
              }
            }
          }
        },
      });
      insertCss(`
              @keyframes ant-line {
                to {
                    stroke-dashoffset: -1000
                }
              }
            `)
      this.graph.fromJSON(data)
      // this.graph.history.redo()
      // this.graph.history.undo()
      // 鼠标移入移出节点
      this.graph.on('node:mouseenter', FunctionExt.debounce(() => {
        console.log('mouseenter');
        const container = document.getElementById('containerChart')
        const ports = container.querySelectorAll(
          '.x6-port-body'
        )
        this.showPorts(ports, true)
      }),
        500
      )
      this.graph.on('node:mouseleave', () => {
        console.log('mouseleave');
        const container = document.getElementById('containerChart')
        const ports = container.querySelectorAll(
          '.x6-port-body'
        )
        this.showPorts(ports, false)
      })
      this.graph.on('blank:click', () => {
        console.log('blank:click');
        this.type = 'grid'
      })
      this.graph.on('cell:click', ({ cell }) => {
        console.log('cell:click', cell, cell.isNode());
        this.type = cell.isNode() ? 'node' : 'edge'
        // 节点点击事件拿到节点的唯一id在attr里面发送请求获取自定义的数据

      })
      this.graph.on('selection:changed', (args) => {
        console.log('selection:changed');
        args.added.forEach(cell => {
          this.selectCell = cell
          if (cell.isEdge()) {
            cell.isEdge() && cell.attr('line/strokeDasharray', 5) //虚线蚂蚁线
            cell.addTools([
              {
                name: 'vertices',
                args: {
                  padding: 4,
                  attrs: {
                    strokeWidth: 0.1,
                    stroke: '#2d8cf0',
                    fill: '#ffffff',
                  }
                },
              },
            ])
          }
        })
        args.removed.forEach(cell => {
          cell.isEdge() && cell.attr('line/strokeDasharray', 0)  //正常线
          cell.removeTools()
        })
      })
    },
    showPorts(ports, show) {
      for (let i = 0, len = ports.length; i < len; i = i + 1) {
        ports[i].style.visibility = show ? 'visible' : 'hidden'
      }
    },
    // 拖拽生成正方形或者圆形
    startDrag(type, e) {
      this.$nextTick(()=>{
        startDragToGraph(this.graph, type, e)
      })
      
    },
    // 删除节点
    deleteNode() {
      const cell = this.graph.getSelectedCells()
      this.graph.removeCells(cell)
      this.type = 'grid'
    },
    // 保存png
    saveToPNG() {
      this.$nextTick(() => {
        this.graph.toPNG((dataUri) => {
          // 下载
          DataUri.downloadDataUri(dataUri, '资产拓扑图.png')
        }, {
          backgroundColor: 'white',
          padding: {
            top: 50,
            right: 50,
            bottom: 50,
            left: 50
          },
          quality: 1,
          copyStyles: false
        })
      })

    },
    // 改变边形状
    changeEdgeType(e) {
      if (e === 'normal') {
        this.connectEdgeType = {
          connector: 'normal',
          router: { name: '' }
        }
        this.currentArrow = 1
      } else if (e === 'smooth') {
        this.connectEdgeType = {
          connector: 'smooth',
          router: { name: '' }
        }
        this.currentArrow = 2
      } else {
        this.connectEdgeType = {
          connector: 'normal',
          router: { name: 'manhattan' }
        }
        this.currentArrow = 3
      }
    },
    // 撤销操作
    beforeStep() {
      this.graph.undo()
    },
    // 恢复撤销的操作
    nextStep() {
      this.graph.redo()
    },
    // 获取节点数据
    getNodeDetail(val) {
      console.log('获取节点数据');
    },
    // 拿到画布数据保存
    saveData() {
      console.log(this.graph.toJSON());
    }
  },
  mounted() {
    this.initX6()
    setTimeout(() => {
      this.showTips = true
    }, 1000)
    setTimeout(() => {
      this.showTips = false
    }, 5000)

    const canvansData = {
      "cells": [
        {
            "shape": "edge",
            "attrs": {
                "line": {
                    "stroke": "#1890ff",
                    "strokeWidth": 1,
                    "targetMarker": {
                        "name": "classic",
                        "size": 8
                    },
                    "strokeDasharray": 0,
                    "style": {
                        "animation": "ant-line 30s infinite linear"
                    }
                }
            },
            "id": "6bef1fab-ecbf-4c94-976c-ae019479671f",
            "labels": [
                {
                    "attrs": {
                        "label": {
                            "text": "88888",
                            "id": ""
                        }
                    }
                }
            ],
            "connector": "normal",
            "router": {
                "name": ""
            },
            "zIndex": 0,
            "source": {
                "cell": "65ca9e31-1236-45ef-a92b-9747c96d49f8",
                "port": "port4"
            },
            "target": {
                "cell": "7e3705d1-bae8-4037-8360-965cac1eafec",
                "port": "port3"
            }
        },
        {
            "position": {
                "x": 798,
                "y": 170
            },
            "size": {
                "width": 100,
                "height": 60
            },
            "attrs": {
                "body": {
                    "stroke": "#000000",
                    "strokeWidth": 1,
                    "fill": "#ffffff"
                },
                "label": {
                    "text": "正方形节点",
                    "fill": "#000000",
                    "fontSize": 14,
                    "id": "",
                    "textWrap": {
                        "width": -10,
                        "height": -10,
                        "ellipsis": true
                    }
                }
            },
            "visible": true,
            "shape": "rect",
            "id": "7e3705d1-bae8-4037-8360-965cac1eafec",
            "zIndex": 2,
            "ports": {
                "groups": {
                    "top": {
                        "position": "top",
                        "attrs": {
                            "circle": {
                                "r": 4,
                                "magnet": true,
                                "stroke": "#2D8CF0",
                                "strokeWidth": 2,
                                "fill": "#fff"
                            }
                        }
                    },
                    "bottom": {
                        "position": "bottom",
                        "attrs": {
                            "circle": {
                                "r": 4,
                                "magnet": true,
                                "stroke": "#2D8CF0",
                                "strokeWidth": 2,
                                "fill": "#fff"
                            }
                        }
                    },
                    "left": {
                        "position": "left",
                        "attrs": {
                            "circle": {
                                "r": 4,
                                "magnet": true,
                                "stroke": "#2D8CF0",
                                "strokeWidth": 2,
                                "fill": "#fff"
                            }
                        }
                    },
                    "right": {
                        "position": "right",
                        "attrs": {
                            "circle": {
                                "r": 4,
                                "magnet": true,
                                "stroke": "#2D8CF0",
                                "strokeWidth": 2,
                                "fill": "#fff"
                            }
                        }
                    }
                },
                "items": [
                    {
                        "id": "port1",
                        "group": "top"
                    },
                    {
                        "id": "port2",
                        "group": "bottom"
                    },
                    {
                        "id": "port3",
                        "group": "left"
                    },
                    {
                        "id": "port4",
                        "group": "right"
                    }
                ]
            }
        },
        {
            "position": {
                "x": 140,
                "y": 140
            },
            "size": {
                "width": 120,
                "height": 120
            },
            "attrs": {
                "label": {
                    "text": "条件节点",
                    "fill": "#000000",
                    "fontSize": 14,
                    "id": "",
                    "textWrap": {
                        "width": -50,
                        "height": "70%",
                        "ellipsis": true
                    }
                },
                "body": {
                    "fill": "#ffffff",
                    "stroke": "#000000",
                    "refPoints": "0,10 10,0 20,10 10,20",
                    "strokeWidth": 1
                }
            },
            "visible": true,
            "shape": "polygon",
            "id": "65ca9e31-1236-45ef-a92b-9747c96d49f8",
            "ports": {
                "groups": {
                    "top": {
                        "position": "top",
                        "attrs": {
                            "circle": {
                                "r": 4,
                                "magnet": true,
                                "stroke": "#2D8CF0",
                                "strokeWidth": 2,
                                "fill": "#fff"
                            }
                        }
                    },
                    "bottom": {
                        "position": "bottom",
                        "attrs": {
                            "circle": {
                                "r": 4,
                                "magnet": true,
                                "stroke": "#2D8CF0",
                                "strokeWidth": 2,
                                "fill": "#fff"
                            }
                        }
                    },
                    "left": {
                        "position": "left",
                        "attrs": {
                            "circle": {
                                "r": 4,
                                "magnet": true,
                                "stroke": "#2D8CF0",
                                "strokeWidth": 2,
                                "fill": "#fff"
                            }
                        }
                    },
                    "right": {
                        "position": "right",
                        "attrs": {
                            "circle": {
                                "r": 4,
                                "magnet": true,
                                "stroke": "#2D8CF0",
                                "strokeWidth": 2,
                                "fill": "#fff"
                            }
                        }
                    }
                },
                "items": [
                    {
                        "id": "port1",
                        "group": "top"
                    },
                    {
                        "id": "port2",
                        "group": "bottom"
                    },
                    {
                        "id": "port3",
                        "group": "left"
                    },
                    {
                        "id": "port4",
                        "group": "right"
                    }
                ]
            },
            "zIndex": 3
        }
    ]
    }
    // this.graph.fromJSON(canvansData)
  }
};
</script>
<style lang="scss">
@import '../../assets/iconfont.css';
@import './index.scss';
</style>